package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseService;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.DictDao;
import com.atguigu.entity.Dict;
import com.atguigu.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = DictService.class)
@Transactional
public class DictServiceImpl extends BaseServiceImpl<Dict> implements DictService {

    @Autowired
    private DictDao dictDao;

    @Override
    protected BaseDao<Dict> getEntityDao() {
        return dictDao;
    }

/* json   [{
        id: '031', name: 'n3.n1', isParent: true
    }, {
        id: '032', name: 'n3.n2', isParent: false
    }, {
        id: '033', name: 'n3.n3', isParent: true
    }, {
        id: '034', name: 'n3.n4', isParent: false
    }]*/

    @Override
    public List<Map<String, Object>> findZnodes(Long parentId) {

        //1查询数据库拿到该节点的所有子节点
        List<Dict> dictList=dictDao.findZnodes(parentId);
        //2进行数据封装,根据json格式来封装List<Map<String, Object>>
        //2.1新建结果容器
        List<Map<String, Object>> zNodes=new ArrayList<>();
        for (Dict dict : dictList) {
            //新建元素结点
            Map<String,Object> node=new HashMap<>();
            node.put("id",dict.getId());
            node.put("name",dict.getName());
            //是否是父节点我们通过根据该ID查询子节点数量去判断
            Integer count= dictDao.countIsParent(dict.getId());
            node.put("isParent",count>0 ? true : false);
            //结点装箱
            zNodes.add(node);
        }
        //3返回封装好的数据
        return zNodes;
    }

    @Override
    public List<Dict> findListByDictCode(String dictCode) {
        //先根据编码查询到该节点ID
        Dict dict =dictDao.getByDictCode(dictCode);
        //根据该节点ID查询拿到子结点数据
        List<Dict> dictList=dictDao.findZnodes(dict.getId());
        return dictList;
    }

    @Override
    public List<Dict> findListByParentId(Long parentId) {
        //1查询数据库拿到该节点的所有子节点
        List<Dict> dictList=dictDao.findZnodes(parentId);
        return dictList;
    }

    @Override
    public String getNameById(Long dictId) {
        return dictDao.getNameById(dictId);
    }
}
